import {useLayoutEffect} from "react";

type RefValue = unknown | undefined | null

export function useImperativeRefer(ref: { current: RefValue } | ((refer: RefValue) => void), refer: RefValue) {
    useLayoutEffect(() => {
        if (typeof ref === 'function') {
            const refCallback = ref;
            refCallback(refer);
            return () => refCallback(null);
        } else if (ref !== null && ref !== undefined) {
            const refObject = ref;
            refObject.current = refer;
            return () => {
                refObject.current = null;
            };
        }
    }, [ref]);
}